    <template>
    <div class="edu-page-warp">
        <el-card shadow="never">
            <el-row>
                <el-col span="12">
                    <div class="edu-page-title">{{$t("message.filterCondition")}}</div>
                </el-col>
                <el-col span="12" >
                    <div class="float-right">
                        {{$t('label.grade')}}：
                        <el-date-picker
                            v-model="year"
                            type="year"
                            value-format="yyyy"
                            :placeholder="$t('message.plzSelect')" style="margin-right:12px">
                        </el-date-picker>
                        <el-button @click="reset">{{ $t("message.reset") }}</el-button>                         
                        <el-button type="primary" @click="filter">{{$t("message.filter")}}</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-card>
        <el-card shadow="never">
             <el-row style="margin-bottom:12px">
                <el-col span="12">
                    <div class="edu-page-title">招生专业设置</div>
                </el-col>
                <el-col span="12">
                   <div class="float-right">
                       <el-button  type="danger" @click="handleClass">预科班管理</el-button>
                       <el-button  type="danger" @click="handleClassStudent">学生预科班关联</el-button>
                       <el-dropdown
                            placement="bottom-start"
                            trigger="click"
                            @command="handleImport"
                        >
                            <el-button>
                                {{ $t('message.import') }}
                                <i class="el-icon-arrow-down el-icon--right"></i>
                            </el-button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item command="down">
                                    {{ $t('message.down') }}
                                </el-dropdown-item>
                                <el-dropdown-item command="import">
                                    {{ $t('message.import') }}
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>                        
                        <el-button  @click="majorExport">{{$t('message.export')}}</el-button>
                        <el-button type="primary" @click="add">{{$t('message.add')}}</el-button>
                   </div>
                </el-col>
             </el-row>
             <edu-table
                :url="getPageListUrl"
                ref="mainTable"
                :order="false"
                :selection="true"
                @selection-change="handleSelectionChange"
            >
                <el-table-column :label="$t('label.grade')"  prop="grade" width="100"/>
                <el-table-column :label="$t('majors.major')" prop="professionName" width="300" show-overflow-tooltip >
                    <template slot-scope="scope">
                        {{scope.row.professionName}} ({{scope.row.profession}})
                    </template>
                </el-table-column>
                <el-table-column label="计划人数"  prop="professionNumber"  width="100"/>
                <el-table-column label="预科生专业" show-overflow-tooltip>
                    <template slot-scope="scope">
                        {{getPreMajorName(scope.row)}}
                    </template>
                </el-table-column>
                 <el-table-column :label="$t('message.operating')" width="100">
                      <template slot-scope="scope">
                        <el-button type="text" @click="editMajor(scope.row)">{{$t('message.edit')}}</el-button>
                        <el-button type="text" @click="deleteMajor(scope.row)">{{$t('message.delete')}}</el-button>
                    </template>
                 </el-table-column>
             </edu-table>
        </el-card>
        <edu-dialog
            :visible.sync="dialogVisible"
            :title="title"
            ref="formDialog"
            @close="closeDialog"
            @confirm="confirmDialog"
            width="600px"
        >
            <el-form :model="submitForm" ref="submitForm" label-width="100px" label-suffix="：" :rules="submitFormRules">
                <el-row>
                      <el-form-item :label="$t('label.grade')" prop="grade">
                          <el-col :span="20">
                               <el-date-picker
                                v-model="submitForm.grade"
                                type="year"
                                style="width:100%"
                                :placeholder="$t('message.plzSelect')"
                                @change="getMajorList"
                                value-format="yyyy"
                                >
                            </el-date-picker>
                          </el-col>
                      </el-form-item>
                </el-row>
                <el-row>
                      <el-form-item :label="$t('majors.major')" prop="profession">
                          <el-col span="20">
                               <DictSelect
                                v-model="submitForm.profession"
                                :data="undergraduateMajor"
                                :filterable="true"
                                ></DictSelect>
                          </el-col>
                      </el-form-item>
                </el-row>
                 <el-row>
                      <el-form-item :label="$t('preparatoryGraduation.recruit.major')" prop="list">
                          <el-col span="20">
                               <DictSelect
                                v-model="submitForm.list"
                                :data="preparatoryMajor"
                                :filterable="true"
                                :multiple="true"
                                ></DictSelect>
                          </el-col>
                      </el-form-item>
                </el-row>
                 <el-row>
                      <el-form-item :label="$t('preparatoryGraduation.recruit.planNum')">
                          <el-col span="20">
                              <el-input-number v-model="submitForm.professionNumber" style="width:100%" :min="1" :max="100" :label="$t('message.inputPlaceholder')"></el-input-number>
                          </el-col>
                      </el-form-item>
                </el-row>
            </el-form>
        </edu-dialog>
        <!--导入-->
        <edu-dialog
            :title="$t('message.import')"
            size="small"
            ref="uploadDialog"
            @close="clearFiles"
            @confirm="uploadFile"
        >
            <el-form  label-width="85px" >
                <el-row>
                    <el-form-item>
                        <el-upload
                            ref="upload"
                            :data="{}"
                            :on-success="uploadDone"
                            :on-error="handleError"
                            :auto-upload="false"
                            :multiple="false"
                            :on-change="(file, fileList)=>{this.importFileList = fileList}"
                            :limit="1"
                            accept=".xls,.xlsx"
                            :action="uploadUrl"
                        >
                            <el-button
                                slot="trigger"
                                size="small"
                                type="primary"
                            >{{$t('label.selectFile')}}</el-button>
                            <div
                                slot="tip"
                                class="el-upload__tip"
                            >只能上传.xls和.xlsx文件</div>
                        </el-upload>
                    </el-form-item>
                </el-row>
            </el-form>
        </edu-dialog>
        <edu-dialog
            :visible.sync="dialogClassVisible"
            title="预科班管理"     
            width="600px"
            :showButtons="false"
        >
            <div>
                <el-form  label-width="65px"  label-suffix="：">
                    <el-row :gutter="20">                    
                        <el-col :span="8">
                            <el-form-item :label="$t('label.grade')">
                                <el-date-picker
                                    v-model="classQueryForm.grade"
                                    type="year"
                                    style="width:100%"
                                    :placeholder="$t('message.plzSelect')"
                                    value-format="yyyy"
                                    :clearable="false"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-button type="primary" @click="classSearch">{{$t('message.filter')}}</el-button>
                        </el-col>
                        <el-col :span="4">
                            <el-button type="danger" @click="handleClassAdd">{{$t('message.add')}}</el-button>
                        </el-col>
                    </el-row>
                    <el-row>
                        <edu-table 
                            :url="getUrl()"
                            ref="classTable"
                            :order="false"
                            :selection="false"
                            :pageSize=5
                            :pageSizes=[5,10,20]
                            >
                            <el-table-column :label="$t('label.grade')" prop="grade" width="150"/>
                            <el-table-column :label="$t('label.name')" prop="className"/>                        
                            <el-table-column :label="$t('message.operating')" width="100">
                                <template slot-scope="scope">
                                    <el-button type="text" @click="handleClassEdit(scope.row)">{{$t("message.edit")}}</el-button>
                                    <el-button type="text" @click="handleClassDelete(scope.row)">{{$t("message.delete")}}</el-button>
                                </template>
                            </el-table-column>
                        </edu-table>
                    </el-row>
                </el-form>
            </div>
        </edu-dialog>
        <!--添加/编辑预科班对话框-->
        <edu-dialog            
            :visible.sync="dialogClassOprVisible"
            width="500px"   
            :title="classForm.id?$t('message.edit'):$t('message.add')"     
             @confirm="confirmClassDialog"
             @close="closeClassDialog"
        >
         <el-form  ref="classForm" :model="classForm" label-width="65px"  label-suffix="：" :rules="classRules">
            <el-row>
                <el-col :span="12">                   
                   <el-form-item :label="$t('label.grade')" prop="grade">
                        <el-date-picker
                            v-model="classForm.grade"
                            type="year"
                            style="width:100%"
                            :placeholder="$t('message.plzSelect')"
                            value-format="yyyy"
                        >
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12">                   
                   <el-form-item :label="$t('label.name')" prop="className">
                       <el-input v-model="classForm.className"  maxlength="30"/>
                    </el-form-item>
                </el-col>
            </el-row>           
        </el-form>
        </edu-dialog>
        <edu-dialog
            :visible.sync="dialogStudentClassVisible"
            title="学生预科班关联"     
            width="700px"
            :showButtons="false"
        >
        <div>
                <el-form  label-width="65px"  label-suffix="：">
                    <el-row :gutter="20">                    
                        <el-col :span="8">
                            <el-form-item :label="$t('label.grade')">
                                <el-date-picker
                                    v-model="classStudentForm.grade"
                                    type="year"
                                    style="width:100%"
                                    :placeholder="$t('message.plzSelect')"
                                    value-format="yyyy"
                                    :clearable="false"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-button type="primary" @click="classStudentSearch">{{$t('message.filter')}}</el-button>
                        </el-col>
                        <el-col :span="8">
                            <el-button  @click="batchBind">批量绑定</el-button>
                            <el-button  @click="batchUnBind">批量取消</el-button>
                        </el-col>
                    </el-row>
                </el-form>
                <el-row>
                        <edu-table 
                            :url="getClassStudentUrl()"
                            ref="classStudentTable"
                            :order="false"
                            :pageSize=10
                            :pageSizes=[10,20]
                            @selection-change="handleSelectionChange"
                        >
                            <el-table-column :label="$t('label.stuCode')" prop="studentId" width="100"/>
                            <el-table-column :label="$t('label.stuName')" prop="studentName" width="200"/>                            
                            <el-table-column label="所在预科班">
                                <template slot-scope="scope">{{scope.row.className}}</template>
                            </el-table-column>                       
                            <el-table-column :label="$t('message.operating')" width="100">
                                <template slot-scope="scope">
                                    <el-button v-if="!scope.row.id" type="text" @click="handleBind(scope.row)">绑定预科班</el-button>
                                    <el-button  v-else type="text" @click="handleUnBind(scope.row)">取消</el-button>
                                </template>
                            </el-table-column>
                        </edu-table>
                </el-row>
        </div>
        </edu-dialog>
        <!--指定学生预科班-->
        <edu-dialog            
            :visible.sync="dialogClassStudentOprVisible"
            title="绑定"     
            @confirm="confirmStudentClassDialog"
            @close="closeStudentClassDialog"
            size="small"
        >
         <el-form  ref="classStudentForm" :model="classStudentForm" label-width="75px"  label-suffix="：" :rules="classStudentRules">
            <el-row>
                <el-col :span="12">                   
                   <el-form-item :label="$t('label.grade')">
                        <el-date-picker
                            v-model="classStudentForm.grade"
                            type="year"
                            style="width:100%"                            
                            value-format="yyyy"
                            :disabled="true"
                        >
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>  
            <el-row>
                <el-col :span="12">                   
                   <el-form-item label="预科班" prop="classId">
                       <el-select 
                        v-model="classStudentForm.classId"
                       style="width:100%" clearable filterable>
                            <el-option v-for="(item,index) in classes" :key="'clz-'+index"  :label="item.label" :value="item.value" />
                       </el-select>
                    </el-form-item>
                </el-col>
            </el-row>          
        </el-form>
        </edu-dialog>
    </div>
</template>
<script>
import {findCampusProfessionList} from "common/src/api/culture/campusProfession";
import * as APIs from "common/src/api/preparatoryGraduation/enroll"
import examinationStudentsApi from "common/src/api/welcomeService/examinationStudents";
export default {
    name: "recruitMajorSetting",
    data() {
        return {
            editId:null,
            year:null,
            defaultYear:null,
            title:null,
            dialogVisible:false,
            selectedRow:null,
            submitForm:{
                grade:null,
                profession:null,
                professionNumber:1,
                list:[]
            },
            submitFormRules:{
                grade:[{
                    required: true,
                    message: this.$t('message.plzSelect'),
                    trigger: "blur"
                }],
                profession:[{
                    required: true,
                    message: this.$t('message.plzSelect'),
                    trigger: "blur"
                }],
                list:[{
                    required: true,
                    message: this.$t('message.plzSelect'),
                    trigger: "blur"
                }],
            },
            undergraduateMajor:[],//本科生专业
            preparatoryMajor:[],//预科生专业
            uploadUrl:null,
            importFileList:[],
            dialogClassVisible:false,
            dialogClassOprVisible:false,
            dialogStudentClassVisible:false,
            dialogClassStudentOprVisible:false,
            classQueryForm:{
                grade:((new Date()).getFullYear()-1).toString()
            },            
            classForm:{
                id:null,
                grade:null,
                className:null
            },
            classRules:{
                grade:[{
                    required: true,
                    message: this.$t('message.plzSelect'),
                    trigger: "blur"
                }],
                className:[{
                    required: true,
                    message: '必须填写',
                    trigger: "blur"
                }],
            },
            classStudentForm:{
                grade:((new Date()).getFullYear()-1).toString(),
                classId:null,
                studentCodes:null
            },
            classStudentRules:{
                classId:[{
                    required: true,
                    message: this.$t('message.plzSelect'),
                    trigger: "blur"
                }]
            },
            multipleSelection:[],
            classMap:new Map(),
            classes:null
        }
    },
    mounted(){
        let now=new Date();
        this.year=now.getFullYear().toString();
        this.defaultYear=this.year;
        this.filter();
    },
    computed:{
        getPageListUrl:function(){
            return APIs.getListPageURL();
        }
    },
    methods:{
        reset(){
            this.year=this.defaultYear;
            this.filter();
        },
        filter(){
            this.$refs.mainTable.search({
                grade:this.year
            })
        },
        add(){
            this.dialogVisible=true;
            this.editId=null;
            this.title=this.$t('message.add');
        },
        closeDialog(){
                this.undergraduateMajor=[]
                this.preparatoryMajor=[];
                this.submitForm.grade=null;
                this.submitForm.profession=null;
                this.submitForm.list=[];
                this.submitForm.professionNumber=1;
                this.$nextTick(()=>{
                    this.$refs.submitForm.clearValidate();
                })
        },
        confirmDialog(){
            this.$refs.submitForm.validate(valid=>{
                if(valid){
                    let param=_.cloneDeep(this.submitForm);
                    param.list=param.list.map(p=>{
                        return {
                            preparatoryProfession:p
                        }
                    })
                    let fn,msg;
                    if(this.editId==null){                        
                        fn=APIs.addSpecialtyPlan;
                        msg=this.$t('message.addSuccess');
                        
                    }else{
                        param.id=this.editId;
                        fn=APIs.editSpecialtyPlan;
                        msg=this.$t('message.editSuccess');
                    }
                    fn(param).then(res=>{
                        if(res.code==200){
                            this.dialogVisible=false;
                            this.$message({
                                type: "success",
                                message: msg
                            });
                            this.filter();
                        }
                    })
                }
            })
        },
        getMajorList(){
            //重置表单与专业列表
            this.undergraduateMajor=[]
            this.preparatoryMajor=[];
            this.submitForm.profession=null;
            this.submitForm.list=[];
            //查询专业列表
            if(this.submitForm.grade){
                //本科生
                findCampusProfessionList({
                        grade:this.submitForm.grade,
                        pageNum_:1,
                        pageSize_:500,
                        projId:'1',
                        trainingLevel:'1'
                    }).then(res=>{
                    if(res.code==200){
                        this.undergraduateMajor=res.data.list.map(major_=>{
                            return {
                                label:major_.professionName+"("+major_.professionCode+")",
                                value:major_.professionCode
                            }
                        })
                    }
                })
                //预科生
                APIs.getClassList(
                    {pageNum_:1,pageSize_:100,condition:{grade:this.submitForm.grade-1 }}              
                ).then(res=>{
                if(res.code==200){
                    this.preparatoryMajor=res.data.list.map(major_=>{
                        return {
                            label:major_.className,
                            value:major_.id.toString()
                        }
                    })

                }
            })
            }           
        },
        editMajor(row){
            this.editId=row.id;
            this.title=this.$t('message.edit')
            this.dialogVisible=true;
            //绑定字段
            this.submitForm.grade=row.grade.toString();            
            this.getMajorList();
            this.submitForm.profession=row.profession;
            this.submitForm.list=row.list.map(major_=>major_.preparatoryProfession);
            this.submitForm.professionNumber=row.professionNumber;
        },
        deleteMajor(row){
            this.$eduConfirm(this.$t('message.areYouSureDelete'), this.$t('message.prompt'))
                .then(() =>{
                    APIs.deleteSpecialtyPlan({id:row.id}).then(res=>{
                        if(res.code==200){
                            this.$message({
                                type: "success",
                                message: this.$t('message.deleteSuccess')
                            });
                            this.filter();
                        }
                    });                    
                })
        },
        majorExport(){
            let loading = this.$loading({
                lock: true,
                text: "Loading",
                spinner: "el-icon-loading",
                background: "rgba(255, 255, 255, .48)"
            });
            if(this.selectedRow==null||this.selectedRow.length==0){
                APIs.exportList({grade:this.year}).then(res=>{
                    if(res.code==200){
                        this.delayRequest(res.data.key,loading);
                    }
                })
            }else{
                APIs.exportSelectedList(this.selectedRow).then(res=>{
                     if(res.code==200){
                        this.delayRequest(res.data.key,loading);
                    }
                })
            }            
        },
        async delayRequest(key, loading) {
            await new Promise(resolve => setTimeout(resolve, 5000));
            examinationStudentsApi.getReportStatus(key)
                .then(res => {
                    if (res.code == 200 && res.data.status) {
                        let path =examinationStudentsApi.exportUrl + res.data.path;
                        window.location.href=path;
                        loading.close();
                    } else {
                        this.delayRequest(key, loading);
                    }
                })
                .catch(ex => {
                    this.delayRequest(key, loading);
                });
        },
        handleSelectionChange(val){
           this.selectedRow=val;
        },
        getPreMajorName(row){
            return row.list.map(major=>major.preparatoryProfessionName).join(',')
        },
        handleImport(cmd){
            if(cmd=='down'){
                window.location.href=APIs.templateDownload();
            }else{
                this.uploadUrl=APIs.importEnrollmentPlan();
                this.$refs.uploadDialog.open()
            }
        },
        clearFiles() {
            this.$refs.upload.clearFiles()
            this.importFileList = []
        },
        uploadFile() {
            if (_.isEmpty(this.importFileList)) {
                this.$message({
                    type: 'info',
                    message: this.$t('message.selectFilePlease')
                })
                return
            }
            this.$refs.upload.submit()
        },
        uploadDone(res, file, importFileList) {
            if (res.code == 200) {
                 this.$message({
                    type: 'success',
                    message: this.$t('uploadSuccess')
                })
                this.filter();
                this.$refs.uploadDialog.close();
            } else {
                this.$message({
                    type: 'error',
                    message: this.$t('common.tips.dataFormatError')
                })
                this.clearFiles()
            }
        },
        handleError(err, file, fileList){
            this.$message({
                type: 'error',
                message: err.message
            })
            this.clearFiles()
        },
        handleClass(){
            this.dialogClassVisible=true;
            this.$nextTick(()=>{
                this.classSearch();
            })            
        },
        getUrl(){
            return APIs.getClassListUrl()
        },
        classSearch(){
            this.$refs.classTable.search({
                grade:this.classQueryForm.grade
            })
        },
        handleClassAdd(){
            this.dialogClassOprVisible=true;
            this.classForm.id=null;
            this.classForm.grade=this.classQueryForm.grade;
        },
        handleClassEdit(row){
            this.dialogClassOprVisible=true;
            this.classForm.id=row.id;
            this.classForm.grade=row.grade.toString();
            this.classForm.className=row.className;
        },
        confirmClassDialog(){
            this.$refs.classForm.validate(valid=>{
                if(valid){
                    let fn=this.classForm.id?APIs.editClass:APIs.addClass;
                    fn(this.classForm).then(res=>{
                        if(res.code == 200){
                            this.$message({
                                type: "success",
                                message: this.$t('message.submitSuccess')
                            });
                            this.dialogClassOprVisible=false;
                            this.classSearch();
                        }
                    });
                }
            });
        },
        closeClassDialog(){
            this.classForm.id=null;
            this.classForm.grade=null;
            this.classForm.className=null;
            this.$nextTick(()=>{
                this.$refs.classForm.clearValidate();
            })
        },
        handleClassDelete(row){
            this.$eduConfirm(this.$t('message.areYouSureDelete'), this.$t('message.prompt'))
            .then(() =>{
                APIs.deleteClass({
                    id:row.id
                }).then(res=>{
                    if(res.code==200){
                        this.$message({
                                type: "success",
                                message: this.$t('message.deleteSuccess')
                        });
                        this.classSearch();
                    }
                })
            })
        },
        //打开学生预科班关联对话框
        handleClassStudent(){
            this.dialogStudentClassVisible=true;
            this.classMap.clear();
            this.$nextTick(()=>{
               this.classStudentSearch();
            })
        },
        classStudentSearch(){
            this.$refs.classStudentTable.search({
                grade:this.classStudentForm.grade
            })
        },
        getClassStudentUrl(){
            return APIs.getClassStudentListUrl();
        },
        //绑定预科班
        handleBind(row){
            this.dialogClassStudentOprVisible=true;
            this.classStudentForm.studentCodes=[row.studentId]
            this.getClasses(this.classStudentForm.grade);
        },
        //取消绑定
        handleUnBind(row){
            this.deleteClassStudent(row.id);
        },
        //批量绑定
        batchBind(){
            if(this.multipleSelection.length==0){
                this.$message({
                    type: "warning",
                    message: '请至少选中一项'
                });
                return;
            }
            this.dialogClassStudentOprVisible=true;
            this.classStudentForm.studentCodes=this.multipleSelection.map(item=>item.studentId)
            this.getClasses(this.classStudentForm.grade);
        },
        //批量取消
        batchUnBind(){
            if(this.multipleSelection.length==0){
                this.$message({
                    type: "warning",
                    message: '请至少选中一项'
                });
                return;
            }
            this.deleteClassStudent(this.multipleSelection.filter(item=>item.id).map(item=>item.id));
        },
        handleSelectionChange(val){
            this.multipleSelection=val;
        },
        confirmStudentClassDialog(){
            this.$refs.classStudentForm.validate(valid=>{
                if(valid){
                    APIs.addClassStudent(this.classStudentForm).then(res=>{
                        if(res.code==200){
                            this.$message({
                                type: "success",
                                message: this.$t('message.submitSuccess')
                            });
                            this.classStudentSearch();
                            this.dialogClassStudentOprVisible=false;
                        }
                    })
                }
            })
        },
        closeStudentClassDialog(){
            this.classStudentForm.classId=null;
            this.classStudentForm.studentCodes=null;
            this.$nextTick(()=>{
                this.$refs.classStudentForm.clearValidate();
            })
        },
        getClasses(val){
            if(this.classMap.has(val)){
                this.classes=this.classMap.get(val);
            }else{
                APIs.getClassList({pageNum_:1,pageSize_:100,condition:{grade:val}}).then(res=>{
                    if(res.code==200&&res.data){
                        this.classes=res.data.list.map(option=>{
                            return {
                                label:option.className,
                                value:option.id
                            }
                        })
                        this.classMap.set(val,_.cloneDeep(this.classes))
                    }
                });                
            }
        },
        deleteClassStudent(ids){
            APIs.deleteClassStudent({ids}).then(res=>{
                if(res.code==200){
                    this.$message({
                        type: "success",
                        message: this.$t('course.operateSuccess')
                    });
                    this.classStudentSearch();
                    this.dialogClassStudentOprVisible=false;
                }
            });
        }
    }
}
</script>